package com.sdu.cloudservice.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/** python调用工具
 * Create by zekdot on 19-6-26.
 */
public class PythonUtil {
    /**
     * 执行python文件并返回是否成功
     * @param filename
     * @return
     */
    public static boolean executePython3(String filename) {
        Process p;
        String cmd = "python3 " + filename;//利用CMD命令调用python，包含两个参数
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            String res;
            res = br.readLine();
            if(res == null){
                return false;
            }
            // System.out.println(res);
            if(res.equals("True")){
                return true;
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public static String queryPython3(String filename,String...args){
        for(String arg : args){
            filename += " " + arg;
        }
        Process p;
        String cmd = "python3 " + filename;
        try {
            p = Runtime.getRuntime().exec(cmd);
//             System.out.println(p.waitFor());
//            Thread.sleep(20000);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            String res;
            res = br.readLine();
            if(res == null){
                return "";
            }

//            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
////             System.out.println(res);
//            String error;
//            System.out.println("ERROR");
//            while ((error = stderrReader.readLine()) != null) {
//                System.out.println(error);
//            }
            return res;
        } catch (IOException e) {
            e.printStackTrace();
        }
//        catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        return null;
    }

    public static void main(String args[]){
        System.out.println(queryPython3("/home/zekdot/桌面/暑期实训/script/价格预测/main.py", "1", "ap-northeast-1a", "ecs.e4.large" ,"2019-06-23T08:00:00Z"));
//        System.out.println(executePython3("/home/zekdot/桌面/暑期实训/script/价格预测/new/linearReg.py"));
//        System.out.println(queryPython3("/home/zekdot/桌面/暑期实训/script/价格预测/new/linearReg.py"));
    }
}
